package com.iretailer.report.config;


import com.iretailer.report.auth.WxenAuthToken;
import com.iretailer.report.model.User;
import com.iretailer.report.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: xjw
 * @Date: 2018/10/10 17:07
 * @Description:
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 获取用户的角色和权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 第三方登录
        if (authenticationToken instanceof WxenAuthToken) {

        }

        /**
         * 获取输入的用户名和密码
         */
        String userName = (String) authenticationToken.getPrincipal();
        String userPwd = new String((char[]) authenticationToken.getCredentials());
        User user = null;
        try {
            user = userService.login(userName, userPwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUserCode, userName));
        if (user == null) {
            throw new UnknownAccountException("User name or password error!");
        }

        return new SimpleAuthenticationInfo(user, user.getUserPwd(), getName());
    }
}
